package com.auto.learning.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.auto.learning.bean.CacheTypeBean;
import com.auto.learning.bean.DownLoadBean;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.ProgressEvent;
import com.auto.learning.net.DownLoadHelper;
import com.auto.learning.net.DownLoadInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FileUtil;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/**
 * 下载服务
 */
public class DownLoadService2 extends Service {
	
	private ArrayList<DownLoadBean> taskQueues = new ArrayList<DownLoadBean>();
	ProgressEvent event = new ProgressEvent();
	private final int BUFFER_SIZE = 16 * 1024;
	private final String FILE_PATH = FileUtil.getFileCachePath() + DownLoadInfo.DOWNLOAD;
	private DownLoadThread downLoadThread;
	private int currentProgress = 0;
	private boolean pause = false;
	private int currentDownLoadBookId = -1;
	
	private Handle handle = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
		};
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		File file = new File(FILE_PATH);
		if (!file.exists()) {
			file.mkdirs();
		}
		registerEvent();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		downLoadThread = new DownLoadThread();
		downLoadThread.start();
		return super.onStartCommand(intent, flags, startId);
	}
	
	int currentLength = 0;
	
	class DownLoadThread extends Thread{
		@Override
		public void run() {
			while (true) {
				while (taskQueues != null && taskQueues.size() > 0) {
					DownLoadBean bean = taskQueues.remove(0);
					File file = new File(FILE_PATH + "/" + bean.getBookId());
					if (!file.exists()) {
						file.mkdir();
					}
					ArrayList<String> mListUrl = bean.getUrlList();
					int loadedLength = bean.getHasDownLoadSize();
					currentProgress = 0;
					while (mListUrl != null && mListUrl.size() > 0) {
						String downLoadUrl = mListUrl.remove(0);
						String fileName = CommonMethod.getFileName(downLoadUrl);
						int totalSize = bean.getTotalSize();
						if (!TextUtils.isEmpty(downLoadUrl)) {
							try {
								//Log.d("downLoadUrl", downLoadUrl);
								InputStream in = DownLoadHelper.getFileInputStream(DownLoadService2.this, downLoadUrl);
								OutputStream out = new FileOutputStream(FILE_PATH + "/" + bean.getBookId() + "/"+ fileName);
								in = new BufferedInputStream(in, BUFFER_SIZE);
								out = new BufferedOutputStream(out, BUFFER_SIZE);
								byte[] buffer = new byte[BUFFER_SIZE];
								int len;
								while ((len = in.read(buffer, 0, BUFFER_SIZE)) > 0) {
									while (pause) {
										try {
											Thread.sleep(500);
										} catch (InterruptedException e) {
											e.printStackTrace();
										}
									}
									out.write(buffer, 0, len);
									loadedLength += len;
									int ratio = (int) ((double)loadedLength / totalSize * 100);
									if (ratio - currentProgress >= 5 || ratio == 0 || ratio == 100) {
										currentDownLoadBookId = bean.getBookId();
										currentProgress = ratio;
										event.setCurrentRatio(currentProgress);
										event.setBookId(bean.getBookId());
										EventBus.getEventBus("downloadProgress").post(event);
										if (currentProgress == 100) {
											currentDownLoadBookId = -1;
											recordDownload(bean.getBookId());
										}
									}
								}
								out.flush();
								if (null != in) {
									in.close();
								}
								if (null != out) {
									out.close();
								}
							} catch (Exception e) {
								e.printStackTrace();
								DownLoadManager.getInstance(DownLoadService2.this).setContext(DownLoadService2.this).addDownLoadId(bean.getBookId());
								break;
							}
						}
					}
				}
				synchronized (this) {
					try {
						TemporaryVariable.temp_download_all_list.clear();
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterEvent();
	}
	
	public boolean isPause() {
		return pause;
	}

	public void setPause(boolean pause) {
		this.pause = pause;
	}
	
	public void recordDownload(int bookId){
		try {
			CacheTypeBean cacheTypeBean = StaticReference.mutilDBSupport.getDao(CacheTypeBean.class).queryBuilder().where().eq("type", 1).and().eq("bookId", bookId).queryForFirst();
			if (cacheTypeBean == null) {
				cacheTypeBean = new CacheTypeBean();
				cacheTypeBean.setBookId(bookId);
				cacheTypeBean.setType(1);
				StaticReference.mutilDBSupport.getDao(CacheTypeBean.class).create(cacheTypeBean);
				if (!TemporaryVariable.downLoadedList.contains(bookId)) {
					TemporaryVariable.downLoadedList.add(bookId);
				}
				EventBus.getEventBus("downloadRefresh").post(0);
				EventBus.getEventBus("download_complete").post(true);
			}

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(DownLoadService2.this, HttpRequestHelper.USERID, 0))));
			params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(bookId)));
			HttpRequestHelper.executeHttpDataNoData(DownLoadService2.this, HttpRequestHelper.BOOK_DOWNLOAD, params, handle, HttpRequestHelper.GETDATA_SUCCESS, -9990);
		
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	@Subscribe
	public void onEventPause(Boolean isPause){
		Log.d("isPause", isPause+"");
		setPause(isPause);
	}
	
	@Subscribe
	public void onEventListDownLoad(DownLoadBean downLoadBean){
		boolean flag = true;
		if (downLoadBean != null) {
			for (DownLoadBean item : taskQueues) {
				if (item.getBookId() == downLoadBean.getBookId()) {
					flag = false;
					break;
				}
			}
			if (flag) {
				taskQueues.add(downLoadBean);
				synchronized (downLoadThread) {
					downLoadThread.notify();
				}
			}
		}
	}
	
	public void registerEvent(){
		EventBus.getEventBus("pause_download", ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("list_download", ThreadEnforcer.MAIN).register(this);
	}
	
	public void unregisterEvent(){
		EventBus.getEventBus("pause_download", ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("list_download", ThreadEnforcer.MAIN).unregister(this);
	}
}
